package com.ramos.kuaixiao.utils;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.ramos.kuaixiao.App;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DateUtil {
    //sharePrefe中保存的定位点时间和登陆时间是否为同一天
    public static boolean isSaveDateSameToLoginDate(){
        if(SharedPreference.hasPreferString("time")){
            if(isSameDate(TimeToDate(Long.valueOf(SharedPreference.getPreferString("time"))), new Date())){
                return true;
            }
        } else {
            return  false;
        }
        return false;
    }

    private static Date TimeToDate(Long time) {
        Date date = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
            String d = format.format(time);
            date = format.parse(d);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }

    public static String dateToString(Date date) {
        String d  = "";
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
            d = format.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return d;
    }

    public static String dateToStr(Date date) {
        String d  = "";
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.CHINA);
            d = format.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return d;
    }

    private static boolean isSameDate(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        boolean isSameYear = cal1.get(Calendar.YEAR) == cal2
                .get(Calendar.YEAR);
        boolean isSameMonth = isSameYear
                && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
        return isSameMonth && cal1.get(Calendar.DAY_OF_MONTH) == cal2
                .get(Calendar.DAY_OF_MONTH);
    }

    public static boolean isNetworkAvailable() {
        ConnectivityManager connectivity = (ConnectivityManager) App.mContext
                .getSystemService(App.mContext.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean isEmptyStr(String str) {
        return str == null || str.length() <= 0;
    }
}
